import SwiftUI
import SPGlassKit

public struct GlassTableExample: GlassExample {
    public static let componentID = "glass-table"

    struct Station: Identifiable {
        let id: String
        let name: String
        let line: String
        let dailyRiders: Int
        let opened: Int
    }

    // Fictitious data.
    private let stations = [
        Station(id: "s1", name: "Harbour Square", line: "Blue", dailyRiders: 48_200, opened: 1987),
        Station(id: "s2", name: "Élan–Université", line: "Green", dailyRiders: 31_750, opened: 2004),
        Station(id: "s3", name: "North Mills", line: "Blue", dailyRiders: 9_640, opened: 1991),
        Station(id: "s4", name: "Parc des Érables", line: "Orange", dailyRiders: 22_310, opened: 2016),
        Station(id: "s5", name: "Old Foundry", line: "Green", dailyRiders: 9_640, opened: 1979),
    ]

    private let columns: [GlassTableColumn<Station>] = [
        GlassTableColumn("Station", id: "name") { $0.name },
        GlassTableColumn("Line", id: "line") { $0.line }
            .badged { _ in .neutral },
        GlassTableColumn("Daily riders", id: "riders", sortingBy: { $0.dailyRiders }) { $0.dailyRiders.formatted(.number) }
            .aligned(.trailing),
        GlassTableColumn("Opened", id: "opened", sortingBy: { $0.opened }) { $0.opened.formatted(.number.grouping(.never)) }
            .aligned(.trailing),
    ]

    @State private var sort: GlassTableSort? = GlassTableSort(columnID: "riders", order: .reverse)
    @State private var selection: Set<String> = ["s2"]
    @State private var showsEmpty = false

    public init() {}

    public var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Toggle("Show the empty state", isOn: $showsEmpty)
            Text("\(selection.count) selected")
                .font(.callout)
                .foregroundStyle(.secondary)
            GlassTable(showsEmpty ? [] : stations, columns: columns, sort: $sort, selection: .multiple($selection), emptyTitle: "No station")
                .frame(minHeight: 320)
        }
        .padding()
    }
}

#Preview("GlassTable") { GlassTableExample() }
